#include <iostream>
#include <unistd.h>
#include <csignal>
#include "Timer_Heap.hpp" // 确保 Timer_Heap 类的头文件路径正确
#include <sys/socket.h>
#include <netinet/in.h>

#include <arpa/inet.h>

volatile sig_atomic_t alarm_triggered = 0;

void timer_handler(int sig)
{
    alarm_triggered = 1;
}

int main()
{
    // 设置信号处理函数
    signal(SIGALRM, timer_handler);

    Timer_Heap timer_heap(10); // 创建一个初始容量为10的定时器堆

    // 创建一些客户端数据
    client_data client1, client2;
    client1.client_timer = new timer(1);
    client1.setsockfd(2578);
    sockaddr_in addr;
    std::string ip = "127.0.0.1";
    int port = 8989;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip.c_str());
    client1.setsockaddr_in(addr);

    client2.client_timer = new timer(5);
    client2.setsockfd(25772);
    sockaddr_in addr1;
    std::string ip1 = "127.0.0.1";
    int port1 = 8922;
    addr1.sin_port = htons(port);
    addr1.sin_addr.s_addr = inet_addr(ip.c_str());
    client2.setsockaddr_in(addr1);

    // 插入定时器
    client1.client_timer->_client_data = &client1;

    client1.client_timer->setfunc(handler);
    client2.client_timer->_client_data = &client2;
    client2.client_timer->setfunc(handler);

    timer_heap.HeapInsert(client1.client_timer);
    timer_heap.HeapInsert(client2.client_timer);

    



    // 主循环
    while (true)
    {
        if (alarm_triggered)
        {
            timer_heap.Handler_heap_timer(); // 调用 Timer_Heap 的方法来处理到期的定时器
            alarm_triggered = 0;
        }

        // 模拟定时器触发
        alarm(1); // 设置1秒后触发SIGALRM信号
        pause();  // 暂停，直到收到信号
    }

    return 0;
}
